import json
import time
from datetime import datetime, timedelta

from flask import session
from sqlalchemy import func, Integer, cast, Date
from sqlalchemy.ext.hybrid import Comparator

from flaskapp.entity.Record import Record
from flaskapp.util.Redprint import Redprint
from flaskapp.util.Result import Result

api = Redprint('punishment')


# 违规处罚功能：
# 1.遍历records表，查询超时的书
#   返回字典如下：用户id,图书id
@api.route('/past_date_remind', methods=['GET'])
def get_past_date_remind():
    past_date_remind = Record.query.with_entities(
        Record.userid,
        Record.bookid
    ).filter(func.now() >= Record.startdate + Record.loandays*1000000).all()
    print(past_date_remind)
    if past_date_remind is None:
        return Result.error(404, 'every book was return'), 404
    else:
        return Result.success(json.dumps(dict(past_date_remind)))


# 2.查询record表中超时的书，并按照每超期一天0.1元给出罚款
#   输出字典的格式：用户id,图书id,罚款
@api.route('/past_date_fine', methods=['GET'])
def get_past_date_fine():

    past_date_fine = Record.query.with_entities(
        Record.userid,
        Record.bookid,
        (func.datediff(cast(func.now(), Date), cast(Record.startdate, Date))-Record.loandays)*0.1
    ).filter(func.now() >= Record.startdate + Record.loandays*1000000).all()

    print(past_date_fine)
    # 将查询结果转换为字典列表
    result_list = []
    for row in past_date_fine:
        result_list.append({
            'userid': row.userid,
            'bookid': row.bookid,
            'fine': row[2]
        })
    # 将字典列表转换为 JSON 格式
    json_data = json.dumps(result_list)

    if past_date_fine is None:
        return Result.error(404, 'every book was return'), 404
    else:
        return Result.success(json_data)
